﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;

/// <summary>
/// 第一個欄位是Button
/// </summary>
public partial class Control_complexGrid1 : System.Web.UI.UserControl
{
    //public event GridViewRowEventHandler RowCreate;       // 資料列建立時期事件
    public event GridViewRowEventHandler RowDataBound;    // 資料列匯入時期事件
    public event GridViewCommandEventHandler RowCommand;  // 資料列執行按鈕事件
    public event GridViewSortEventHandler Sorting;        // 欄位排序事件
    public event GridViewPageEventHandler Pageindexchanging;
    public event EventHandler DataBound;


    protected Dictionary<string, int> sortList = null;
             

    [Description("設定PageSize"), Category("MISAPP"), DefaultValue(10)]
    public int PageSize
    {
        set
        {
            if (this.PageSize != value)
            {
                this.ViewState["PageSize"] = value;
            }
            if (value == 0)
            {
                value =(int)Utility.GetAttributeDefaultValue("PageSize", this);
            }
            GV1.PageSize = value;
        }
        get
        {
            object obj2 = this.ViewState["PageSize"];
            if (obj2 != null)
            {
                return (int)obj2;
            }
            return 10;
        }

    }

    [Description("是否允許分頁"), Category("MISAPP"), DefaultValue(false)]
    public bool AllowPaging
    {
        set
        {
            GV1.AllowPaging = value;
        }
        get
        {
            return GV1.AllowPaging;
        }
    }

    [Description("是否允許排序"), Category("MISAPP"), DefaultValue(false)]
    public bool AllowSorting
    {
        set
        {
            GV1.AllowSorting = value;
        }
        get
        {
            return GV1.AllowSorting;
        }
    }

    [Description("設定GridView中的 Caption"), Category("MISAPP"), DefaultValue("")]
    public string Caption
    {
        set
        {
            GV1.Caption = value;
        }
    }

    [Description("設定GridView中的 td 是數字要用的 CSS 名稱"), Category("MISAPP"), DefaultValue("")]
    public string NumberCSS
    {
        set;
        get;
    }

    [Description("設定GridView中的 td 是文字要用的 CSS 名稱"), Category("MISAPP"), DefaultValue("")]
    public string StringCSS
    {
        set;
        get;
    }

    [Description("設定GridView中的第一個Button 中要顯示的是文字"), Category("MISAPP"), DefaultValue("...")]
    public string ButtonText
    {
        set
        {
            if (this.ButtonText != value)
            {
                this.ViewState["ButtonText"] = value;
            }
        }
        get
        {
            object obj2 = this.ViewState["ButtonText"];
            if (obj2 != null)
            {
                return obj2.ToString();
            }
            else
            {
                object obj = Utility.GetAttributeDefaultValue("ButtonText", this);
                return obj.ToString();
            }
        }
    }

    [Description("設定GridView中的第一個Button 中是否要顯示"), Category("MISAPP"), DefaultValue(true)]
    public bool ShowFirstButton
    {
        set
        {
            if (this.ShowFirstButton != value)
            {
                this.ViewState["ShowFirstButton"] = value;
            }
        }
        get
        {
            object obj2 = this.ViewState["ShowFirstButton"];
            if (obj2 != null)
            {
                return (bool)obj2;
            }
            else
            {
                object obj = Utility.GetAttributeDefaultValue("ShowFirstButton", this);
                return (bool)obj;
            }
        }       
    }

    protected SortDirection GVSortDirection
    {
        get
        {
            if (ViewState["sortDirection"] == null)
            {
                ViewState["sortDirection"] = SortDirection.Ascending;
            }
            return (SortDirection)ViewState["sortDirection"];            
        }
        set
        {
            ViewState["sortDirection"] = value;
        }
    }

    protected System.Data.DataTable dt = null;
    
    protected string[] keyList = null;
    public Dictionary<string, string> SelectKeyValue = new Dictionary<string,string>();

    protected void Page_Load(object sender, EventArgs e)
    {

    }
   

    #region GridView Method

    protected void GV1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (this.ShowFirstButton == false)
        {
            if ((e.Row.RowType == DataControlRowType.Header) || 
                (e.Row.RowType == DataControlRowType.DataRow))
            {
                e.Row.Cells.Remove(e.Row.Cells[0]);
            }
        }

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //在這裏把ROWID 填入到CommandArgument
            FillCommandArgument(e);
            //SetCellFormat(e);        
        }
        if (RowDataBound != null) this.RowDataBound(sender, e);
    }

    protected void GV1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "detail")
        {            
            string[] args = e.CommandArgument.ToString().Split(new Char[] { ',' }
                ,StringSplitOptions.RemoveEmptyEntries);
            string[] strKV = null;
            foreach (string s in args)
            {
                strKV = s.Split(new Char[] {'='} );
                if (strKV.Length > 0)
                {
                    SelectKeyValue.Add(strKV[0], strKV[1]);
                }                                    
            }           
        }
        if (RowCommand != null) this.RowCommand(sender, e);
    }

    protected void GV1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GV1.PageIndex = e.NewPageIndex;
        if(Pageindexchanging != null)
        {
            Pageindexchanging(sender, e);
        }
    }

    protected void GV1_Sorting(object sender, GridViewSortEventArgs e)
    {
        //先取回資料，再在重新排序!!
        if (Sorting != null) this.Sorting(sender, e);

        string sortExpression, sort;
        sortExpression = e.SortExpression.ToLower();//取得欄位
        GVSortDirection = (GVSortDirection == SortDirection.Ascending)
            ?GVSortDirection = SortDirection.Descending
            :GVSortDirection = SortDirection.Ascending;

        sort = GVSortDirection == SortDirection.Ascending ? "ASC" : "DESC";
        //--先取回資料
        if (Sorting != null)
        {
            Sorting(sender, e);
        }
        
        dt.DefaultView.Sort = string.Format("{0} {1}",sortExpression,sort);
        GV1.DataSource = dt.DefaultView;
        GV1.DataBind();
    }

    protected void GV1_DataBound(object sender, EventArgs e)
    {
        if (DataBound != null)
        { DataBound(sender, e); }
        if (sortList != null)
        {
            if (GV1.Rows.Count.Equals(0))
            { return; }
            foreach (KeyValuePair<string, int> kv in sortList)
            {
                GV1.HeaderRow.Cells[kv.Value].Text = kv.Key;
            }        
        }
    }


    #endregion

    #region 自訂Method
    
    /// <summary>
    /// 
    /// </summary>
    /// <param name="p_dt"></param>
    /// <param name="p_keyList"></param>
    public void SetData(System.Data.DataTable p_dt, string[] p_keyList)
    {
        dt = p_dt;
        keyList = p_keyList;
        GV1.DataSource = p_dt;
        GV1.DataBind();
    }

    public void SetData(System.Data.DataTable p_dt)
    {
        this.SetData(p_dt, null);
    }

    protected void FillCommandArgument(GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (this.ShowFirstButton == true)
            {
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                Button btn = e.Row.Cells[0].Controls[1] as Button;
                btn.Text = ButtonText;
                foreach (string s in keyList)
                {
                    sb.AppendFormat(",{0}={1}", s, dt.Rows[GetCurrentTableIndex(e.Row.RowIndex)][s], ToString());
                }
                btn.CommandArgument = sb.ToString();
            }
            else
            {
               // e.Row.Cells.Remove(e.Row.Cells[0]);
                
            }
        }
    }

    protected int GetCurrentTableIndex(int p_rowIndex)
    {
        int rtnValue = 0;
        if (GV1.PageIndex == 0)
        {
            rtnValue = p_rowIndex;
        }
        else
        {
            rtnValue = GV1.PageSize * GV1.PageIndex + p_rowIndex;
        }
        return rtnValue;
    }

    protected void SetCellFormat(GridViewRowEventArgs e)
    {
        if (e.Row.RowType != DataControlRowType.DataRow)
        {return;}
        int i = 0;
        foreach (System.Data.DataColumn col in dt.Columns)
        {
            if (e.Row.Cells[i].Text.Length > 0)
            {
                switch (col.DataType.ToString())
                {
                    case "System.Int16":                    
                    case "System.Int32":
                    case "System.Int64": 
                        e.Row.Cells[i].CssClass = NumberCSS;
                        e.Row.Cells[i].Text = GetCommaString(col.DataType.ToString()
                            ,e.Row.Cells[i].Text);
                        break;
                    case "System.Double":
                        e.Row.Cells[i].CssClass = NumberCSS;
                        e.Row.Cells[i].Text = GetCommaString(col.DataType.ToString()
                             , e.Row.Cells[i].Text);                                
                        break;
                    case "System.Decimal":
                        e.Row.Cells[i].CssClass = NumberCSS;
                        e.Row.Cells[i].Text = GetCommaString(col.DataType.ToString()
                            ,e.Row.Cells[i].Text);
                        break;
                    case "System.String":
                        e.Row.Cells[i].CssClass = StringCSS;
                        break;
                }
            }
            i++;
        }        
    }

    protected string GetCommaString(string p_type, string p_value)
    {
        string rtnValue = string.Empty;
        switch (p_type)
        {
            case "System.Int16":
            case "System.Int32":
            case "System.Int64":
                rtnValue = String.Format("{0:###,###,##0}", int.Parse(p_value));
                break;
            case "System.Decimal":
                String.Format("{0:###,###,##0.00}", decimal.Parse(p_value));
                break;
            case "System.Double":
                if (double.Parse("100") < double.Parse(p_value)) //沒有大於100不設comma
                {
                    rtnValue = String.Format("{0:###,###,##0}", double.Parse(p_value));
                }
                else
                {
                    rtnValue = p_value;
                }
                break;
        }
        return  rtnValue;
    }


    public void AddNotSort(string p_header,int p_pos)
    {
        if (sortList == null)
        {
            sortList = new Dictionary<string, int>();
        }
        sortList.Add(p_header, p_pos);
    }

    #endregion
}
